﻿Imports System.Data.SqlClient

Public Class CBackupRestoreDAO

    Private Function Connect() As SqlConnection
        Dim strCon As String = "server=(local);"
        strCon += "database=master"
        strCon += ";uid=sa"
        strCon += ";pwd=123;"
        Dim cn As New SqlConnection(strCon)
        cn.Open()
        Return cn
    End Function

    Public Function BackupDatabase(ByVal _name As String, ByVal _path As String) As Boolean
        Dim exist As Boolean = False

        Dim strSQL As String = "select  name from master.dbo.sysdevices   "
        strSQL += " where name = '" & CDataProvider.database & "'"
        Dim Con As SqlConnection = Connect()
        Dim Com As New SqlCommand(strSQL, Con)
        Try
            strSQL = "BACKUP DATABASE  [" & CDataProvider.database & "] TO  DISK = '" & _path & "'"
            Com = New SqlCommand(strSQL, Con)
            Com.ExecuteNonQuery()
            Con.Close()
            exist = True
        Catch ex As Exception
            If Con.State <> ConnectionState.Closed Then
                Con.Close()
            End If
            exist = False
        Finally
            Con.Dispose()
        End Try
        Return exist
    End Function

    Public Function RestoreDatabase(ByVal _path As String) As Boolean
        Dim exist As Boolean = False
        Dim sqlDelete As String = "ALTER DATABASE QLTV SET SINGLE_USER WITH ROLLBACK IMMEDIATE  IF EXISTS (SELECT name FROM sys.databases WHERE name = N'QLTV') BEGIN drop database [QLTV] End"

        Dim sqlRestore As String = "Use master Restore Database [" & CDataProvider.database & "] from disk='" & _path & "'"
        Dim con As SqlConnection = Connect()
        Dim cmd As New SqlCommand(sqlRestore, con)
        Dim cmddelete As New SqlCommand(sqlDelete, con)
        'Dim cn As SqlConnection = CDataProvider.Connect()
        'cn.Close()
        Try
            cmddelete.ExecuteNonQuery()
            cmd.ExecuteNonQuery()
            con.Close()
            exist = True
        Catch ex As Exception
            exist = False
            con.Close()
        End Try
        Return exist
    End Function

   

End Class
